﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.Enum;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Domains.zjy;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;
using Yitter.IdGenerator;

namespace RearLivestock.Beginning.Api.Application.Command.BreedingSow
{
    public class CreateBreedingSowHandler : IRequestHandler<CreateBreedingSowCommand, Result>
    {
        /// <summary>
        /// 基本信息仓储
        /// </summary>
        private readonly IBaseRepository<BasicInformation> _basicInformationrepository;

        /// <summary>
        /// 种母期初
        /// </summary>
        private readonly IBaseRepository<BreedingSows> _breedingSowsRepository;

        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper _mapper;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateBreedingSowHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="basicInformationrepository"></param>
        /// <param name="breedingSowsRepository"></param>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        public CreateBreedingSowHandler(
            IBaseRepository<BasicInformation> basicInformationrepository,
            IBaseRepository<BreedingSows> breedingSowsRepository,
            IMapper mapper,
            ILogger<CreateBreedingSowHandler> logger)
        {
            _basicInformationrepository = basicInformationrepository;
            _breedingSowsRepository = breedingSowsRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(CreateBreedingSowCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var num = 1001;
                foreach (var item in request.BreedingSows)
                {
                    //循环添加流水号 雪花ID
                    item.SerialNumber = YitIdHelper.NextId().ToString();
                    //循环添加单据号
                    item.DocumentNumber = DateTime.Now.ToString("yyyyMMddHHmmss") + num;
                    num++;
                    //根据前台传入的耳号id进行查询
                    var query = await (await _basicInformationrepository.GetAll()).Where(x => x.BasicInforId == item.BasicInforId).ToListAsync();
                    //循环修改猪只档案(基本信息) 种母的 栋舍 栏位 在场状态 入场时间
                    query.ForEach(x =>
                    {
                        x.BedroomId = item.BedroomId;
                        x.FieldId = item.FieldId;
                        x.Presentstatus = PresentstatusEnums.在场;
                        x.EntryDate = DateTime.Now;
                    });
                    //修改猪只档案信息
                    _basicInformationrepository.UpdRange(query);
                }
                //BreedingSows breedingsow = _mapper.Map<BreedingSows>(request);
                var res = _breedingSowsRepository.AddRange(request.BreedingSows);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加种母期初成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "添加种母期初异常" + ex.Message;
                _logger.LogError("添加种母期初异常" + ex.Message);
            }
            return result;
        }
    }
}
